using System;
using System.Collections;
using System.Collections.Generic;
using FGUFW.Core;
using UnityEngine;

namespace FGUFW.Play
{
    abstract public class PlayManager<T> : MonoBehaviour,IPlayManager where T : PlayManager<T>
    {
        Dictionary<Type,IPlayModule> _modelDict = new Dictionary<Type, IPlayModule>(); 

        public U Module<U>() where U : IPlayModule
        {
            Type type = typeof(U);
            if(!_modelDict.ContainsKey(type))
            {
                IPlayModule client = Activator.CreateInstance(type) as IPlayModule;
                _modelDict[type]=client;
            }
            return (U)_modelDict[type];
        }

        public void Release()
        {
            foreach (var model in _modelDict)
            {
                model.Value.Release();
            }
            _modelDict.Clear();
        }

        
		private static T mInstance = null;

		public static T I
		{
			get
			{
				if (mInstance == null)
				{
					mInstance = GameObject.FindObjectOfType(typeof(T)) as T;
					if (mInstance == null)
					{
						string parentName = "MonoSingleton";
						GameObject go = new GameObject(typeof(T).Name);
						mInstance = go.AddComponent<T>();
						GameObject parent = GameObject.Find(parentName);
						if (parent == null)
						{
							parent = new GameObject(parentName);
						}
						if (parent != null)
						{
							go.transform.parent = parent.transform;
						}
					}
				}

				return mInstance;
			}
		}


		private void Awake()
		{
			if (mInstance == null)
			{
				mInstance = this as T;
			}

			Init();
		}
	
		protected virtual void Init()
		{

		}
    }
}